package com.hjm.common.utils;

import java.util.*;

public class DigestUtils {

    private final static String KEY ="liandongupay1a6a43b062e87d5e6ad59b6b5757734d";
    private final int[] ABCDE = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 };

    /**
     * 摘要数据存储数组
     */
    private int[] digestInt = new int[5];

    /**
     * 计算过程中的临时数据存储数组
     */
    private int[] tmpData = new int[80];

    /**
     * 计算sha-1摘要
     * @author: wangzw
     * @version: 1.0
     * @date: 2018/6/16 15:21
     */
    private int processInputBytes(byte[] byteData) {
        System.arraycopy(ABCDE, 0, digestInt, 0, ABCDE.length);
        byte[] newByte = byteArrayFormatData(byteData);
        int mcount = newByte.length / 64;
        for (int pos = 0; pos < mcount; pos++) {
            for (int j = 0; j < 16; j++) {
                tmpData[j] = byteArrayToInt(newByte, (pos * 64) + (j * 4));
            }
            encrypt();
        }
        return 20;
    }

    /**
     * 格式化输入字节数组格式
     * @author: wangzw
     * @version: 1.0
     * @date: 2018/6/16 15:22
     */
    private byte[] byteArrayFormatData(byte[] byteData) {
        // 补0数量
        int zeros = 0;
        // 补位后总位数
        int size = 0;
        // 原始数据长度
        int n = byteData.length;
        // 模64后的剩余位数
        int m = n % 64;
        // 计算添加0的个数以及添加10后的总长度
        if (m < 56) {
            zeros = 55 - m;
            size = n - m + 64;
        } else if (m == 56) {
            zeros = 63;
            size = n + 8 + 64;
        } else {
            zeros = 63 - m + 56;
            size = (n + 64) - m + 64;
        }
        // 补位后生成的新数组内容
        byte[] newByte = new byte[size];
        // 复制数组的前面部分
        System.arraycopy(byteData, 0, newByte, 0, n);
        // 获得数组Append数据元素的位置
        int l = n;
        // 补1操作
        newByte[l++] = (byte) 0x80;
        // 补0操作
        for (int i = 0; i < zeros; i++) {
            newByte[l++] = (byte) 0x00;
        }
        // 计算数据长度，补数据长度位共8字节，长整型
        long N = (long) n * 8;
        byte h8 = (byte) (N & 0xFF);
        byte h7 = (byte) ((N >> 8) & 0xFF);
        byte h6 = (byte) ((N >> 16) & 0xFF);
        byte h5 = (byte) ((N >> 24) & 0xFF);
        byte h4 = (byte) ((N >> 32) & 0xFF);
        byte h3 = (byte) ((N >> 40) & 0xFF);
        byte h2 = (byte) ((N >> 48) & 0xFF);
        byte h1 = (byte) (N >> 56);
        newByte[l++] = h1;
        newByte[l++] = h2;
        newByte[l++] = h3;
        newByte[l++] = h4;
        newByte[l++] = h5;
        newByte[l++] = h6;
        newByte[l++] = h7;
        newByte[l++] = h8;
        return newByte;
    }

    private int f1(int x, int y, int z) {
        return (x & y) | (~x & z);
    }

    private int f2(int x, int y, int z) {
        return x ^ y ^ z;
    }

    private int f3(int x, int y, int z) {
        return (x & y) | (x & z) | (y & z);
    }

    private int f4(int x, int y) {
        return (x << y) | x >>> (32 - y);
    }

    /**
     * 单元摘要计算函数
     * @author: wangzw
     * @version: 1.0
     * @date: 2018/6/16 15:22
     */
    private void encrypt() {
        for (int i = 16; i <= 79; i++) {
            tmpData[i] = f4(tmpData[i - 3] ^ tmpData[i - 8] ^ tmpData[i - 14] ^ tmpData[i - 16], 1);
        }
        int[] tmpAbcde = new int[5];
        for (int i1 = 0; i1 < tmpAbcde.length; i1++) {
            tmpAbcde[i1] = digestInt[i1];
        }
        for (int j = 0; j <= 19; j++) {
            int tmp = f4(tmpAbcde[0], 5) + f1(tmpAbcde[1], tmpAbcde[2], tmpAbcde[3]) + tmpAbcde[4]  + tmpData[j] + 0x5a827999;
            tmpAbcde[4] = tmpAbcde[3];
            tmpAbcde[3] = tmpAbcde[2];
            tmpAbcde[2] = f4(tmpAbcde[1], 30);
            tmpAbcde[1] = tmpAbcde[0];
            tmpAbcde[0] = tmp;
        }
        for (int k = 20; k <= 39; k++) {
            int tmp = f4(tmpAbcde[0], 5) + f2(tmpAbcde[1], tmpAbcde[2], tmpAbcde[3]) + tmpAbcde[4] + tmpData[k] + 0x6ed9eba1;
            tmpAbcde[4] = tmpAbcde[3];
            tmpAbcde[3] = tmpAbcde[2];
            tmpAbcde[2] = f4(tmpAbcde[1], 30);
            tmpAbcde[1] = tmpAbcde[0];
            tmpAbcde[0] = tmp;
        }
        for (int l = 40; l <= 59; l++) {
            int tmp = f4(tmpAbcde[0], 5) + f3(tmpAbcde[1], tmpAbcde[2], tmpAbcde[3]) + tmpAbcde[4] + tmpData[l] + 0x8f1bbcdc;
            tmpAbcde[4] = tmpAbcde[3];
            tmpAbcde[3] = tmpAbcde[2];
            tmpAbcde[2] = f4(tmpAbcde[1], 30);
            tmpAbcde[1] = tmpAbcde[0];
            tmpAbcde[0] = tmp;
        }
        for (int m = 60; m <= 79; m++) {
            int tmp = f4(tmpAbcde[0], 5) + f2(tmpAbcde[1], tmpAbcde[2], tmpAbcde[3]) + tmpAbcde[4] + tmpData[m] + 0xca62c1d6;
            tmpAbcde[4] = tmpAbcde[3];
            tmpAbcde[3] = tmpAbcde[2];
            tmpAbcde[2] = f4(tmpAbcde[1], 30);
            tmpAbcde[1] = tmpAbcde[0];
            tmpAbcde[0] = tmp;
        }
        for (int i2 = 0; i2 < tmpAbcde.length; i2++) {
            digestInt[i2] = digestInt[i2] + tmpAbcde[i2];
        }
        for (int n = 0; n < tmpData.length; n++) {
            tmpData[n] = 0;
        }
    }

    /**
     * 4字节数组转换为整数
     * @author: wangzw
     * @version: 1.0
     * @date: 2018/6/16 15:23
     */
    private int byteArrayToInt(byte[] byteData, int i) {
        return ((byteData[i] & 0xff) << 24) | ((byteData[i + 1] & 0xff) << 16)
                | ((byteData[i + 2] & 0xff) << 8) | (byteData[i + 3] & 0xff);
    }

    /**
     * 整数转换为4字节数组
     * @author: wangzw
     * @version: 1.0
     * @date: 2018/6/16 15:24
     */
    private void intToByteArray(int intValue, byte[] byteData, int i) {
        byteData[i] = (byte) (intValue >>> 24);
        byteData[i + 1] = (byte) (intValue >>> 16);
        byteData[i + 2] = (byte) (intValue >>> 8);
        byteData[i + 3] = (byte) intValue;
    }

    /**
     * 将字节转换为十六进制字符串
     * @author: wangzw
     * @version: 1.0
     * @date: 2018/6/16 15:24
     */
    private String byteToHexString(byte ib) {
        char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F' };
        char[] ob = new char[2];
        ob[0] = digit[(ib >>> 4) & 0X0F];
        ob[1] = digit[ib & 0X0F];
        return new String(ob);
    }

    /**
     * 将字节数组转换为十六进制字符串
     * @author: wangzw
     * @version: 1.0
     * @date: 2018/6/16 15:24
     */
    private String byteArrayToHexString(byte[] byteArray) {
        StringBuilder strDigest = new StringBuilder();
        for (byte aByteArray : byteArray) {
            strDigest.append(byteToHexString(aByteArray));
        }
        return strDigest.toString();
    }

    /**
     * 计算sha-1摘要，返回相应的字节数组
     * @author: wangzw
     * @version: 1.0
     * @date: 2018/6/16 15:24
     */
    private byte[] getDigestOfBytes(byte[] byteData) {
        processInputBytes(byteData);
        byte[] digest = new byte[20];
        for (int i = 0; i < digestInt.length; i++) {
            intToByteArray(digestInt[i], digest, i * 4);
        }
        return digest;
    }

    /**
     * 计算sha-1摘要，返回相应的十六进制字符串
     * @author: wangzw
     * @version: 1.0
     * @date: 2018/6/16 15:24
     */
    private String getDigestOfString(byte[] byteData) {
        return byteArrayToHexString(getDigestOfBytes(byteData));
    }

    public String encodeShaHexStr(String data){
        try{
            return new DigestUtils().getDigestOfString((data.concat(KEY)).getBytes("UTF-8")).toLowerCase();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 计算MAC
     * @author: wangzw
     * @version: 1.0
     * @date: 2018/6/16 15:25
     */
    public static String encodeShaHexStr(Map<String,Object> dataMap){
        try{
            if(dataMap == null || dataMap.size() == 0) {
                return "";
            }
            Collection<String> keySet = dataMap.keySet();
            List<String> list = new ArrayList<>(keySet);
            Collections.sort(list);
            StringBuilder stringBuffer = new StringBuilder();
            for(int i=0; i< list.size();i++){
                stringBuffer.append(list.get(i)).append("=").append(("null".equals(dataMap.get(list.get(i))) || null == dataMap.get(list.get(i))) ? "" : dataMap.get(list.get(i))).append("&");
            }
            String data = stringBuffer.toString().substring(0,stringBuffer.toString().length()-1);
            return new DigestUtils().getDigestOfString((data.concat(KEY)).getBytes("UTF-8")).toLowerCase();
        }catch(Exception e){
            e.printStackTrace();
        }
        return "";
    }
    
}
